import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_2d_amap/flutter_2d_amap.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/utils/color_utils.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/activity/activity_create_request.dart';
import 'package:flutterlib/pages/activity/base_activity_create_page.dart';
import 'package:flutterlib/widgets/calendar_view.dart';
import 'package:flutterlib/widgets/editor/editor_view.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:rounded_loading_button/rounded_loading_button.dart';
import 'package:smart_select/smart_select.dart';
import 'package:thrio/thrio.dart';

//兴趣活动
class Page extends BaseActivityCreatePage {
  //传入小圈id
  final int circleId;
  final int interestId;

  const Page({this.interestId, Key key, this.circleId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ActivityCreatePageState();
  }
}

class _ActivityCreatePageState extends BaseActivityCreatePageState<Page> {
  ActivityForm _activityForm;
  ActivityIsOnline _activityIsOnline;
  PoiSearch _poiSearch;

  TextEditingController priceController = TextEditingController();
  final FocusNode costFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
  }

  Widget get selectIsOnline {
    var choice = ActivityIsOnline.values
        .map((e) => S2Choice<ActivityIsOnline>(value: e, title: e.title))
        .toList();
    return SmartSelect<ActivityIsOnline>.single(
      title: '是否线上',
      value: _activityIsOnline,
      placeholder: '线下',
      choiceItems: choice,
      onChange: (state) {
        unFocusTextField();
        setState(() => _activityIsOnline = state.value);
      },
      modalType: S2ModalType.bottomSheet,
      modalFilter: false,
      tileBuilder: (context, state) {
        return S2Tile.fromState(
          state,
          padding: EdgeInsets.all(0),
          isTwoLine: false,
        );
      },
    );
  }

  Widget get selectActivityForm {
    var choice = ActivityForm.values
        .map((e) => S2Choice<ActivityForm>(value: e, title: e.title))
        .toList();
    // SmartSelect<String>.single(
    //   title: 'Days',
    //   value: _day,
    //   choiceItems: choices.days,
    //   onChange: (state) => setState(() => _day = state.value),
    //   tileBuilder: (context, state) {
    //     return S2Tile.fromState(
    //       state,
    //       isTwoLine: true,
    //     );
    //   },
    // ),
    return SmartSelect<ActivityForm>.single(
      title: '形式',
      value: _activityForm,
      placeholder: '研讨会',
      choiceItems: choice,
      onChange: (state) {
        unFocusTextField();
        setState(() => _activityForm = state.value);
      },
      modalType: S2ModalType.bottomSheet,
      modalFilter: true,
      tileBuilder: (context, state) {
        return S2Tile.fromState(
          state,
          isTwoLine: false,
          padding: EdgeInsets.all(0),
        );
      },
    );
  }

  Widget fillIntro() {
    const double inset = 20;
    return Container(
        padding: EdgeInsets.only(left: inset, right: inset),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
                padding: EdgeInsets.only(top: inset, bottom: inset),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        STATIC_STRING_TITLE,
                        style: TextStyle(fontSize: 16),
                      ),
                      SizedBox(
                          height: 20,
                          child: Image.asset("assets/images/edit.png"))
                    ])),
            TextField(
              decoration: InputDecoration(
                  hintText: STATIC_STRING_TITLE_HINT, border: InputBorder.none),
              controller: titleController,
              autofocus: false,
              focusNode: titleFocusNode,
            ),
            Divider(
              height: 1,
            ),
            selectIsOnline,
            (_activityIsOnline?.value ?? 0) == 0
                ? Padding(
                    padding: EdgeInsets.only(bottom: inset),
                    child: Text(STATIC_STRING_ADDRESS,
                        style: TextStyle(fontSize: 16)))
                : Container(),
            (_activityIsOnline?.value ?? 0) == 0
                ? getSelectWidget((_poiSearch?.title) ?? '', () async {
                    // Map<Permission, PermissionStatus> statuses = await [
                    //   Permission.location,
                    //   Permission.storage,
                    // ].request();
                    unFocusTextField();
                    if (await Permission.location.request().isGranted) {
                      // Either the permission was already granted before or the user just granted it.
                      NavigatorUtils.gotoSelectAddress(context, (params) {
                        var poiSearch =
                            PoiSearch.fromJsonMap(jsonDecode(params));
                        setState(() {
                          _poiSearch = poiSearch;
                        });
                        trueDebugPrint("flutterting ${poiSearch.title}");
                      });
                    }
                  })
                : Container(),
            Padding(
                padding: EdgeInsets.only(top: inset, bottom: inset),
                child: Text(STATIC_STRING_TIME)),
            getSelectWidget(dateTimeFormat, () {
              unFocusTextField();
              showCalendarDialog(context, startTime, endTime, (start, end) {
                setState(() {
                  startTime = start;
                  endTime = end;
                });
              });
            }),
            selectActivityForm,
            SizedBox(
              height: inset,
            ),
            Row(children: [
              Expanded(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                    Text(STATIC_STRING_PERSON_NUMBER,
                        style: TextStyle(fontSize: 16)),
                    TextField(
                      controller: personNumberController,
                      focusNode: personCountfocusNode,
                      decoration: InputDecoration(
                          hintText: "0", border: InputBorder.none),
                      keyboardType: TextInputType.number,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    ),
                    Divider(
                      height: 1,
                    )
                  ])),
              SizedBox(
                width: 16,
              ),
              Expanded(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                    Text(STATIC_STRING_PRICE, style: TextStyle(fontSize: 16)),
                    TextField(
                      controller: priceController,
                      focusNode: costFocusNode,
                      decoration: InputDecoration(
                          hintText: "0", border: InputBorder.none),
                      keyboardType: TextInputType.text,
                    ),
                    Divider(
                      height: 1,
                    )
                  ])),
            ]),
            Padding(
                padding: EdgeInsets.only(top: inset, bottom: inset),
                child: Text(STATIC_STRING_FILL_DESCRIPATION,
                    style: TextStyle(fontSize: 16))),
            Container(
                decoration: BoxDecoration(
                    color: HexColor("#E0E0E0"),
                    borderRadius: BorderRadius.circular(4)),
                height: 200,
                child: EditorView(
                  focusNode: descFocusNode,
                  controller: editorController,
                )),
            SizedBox(
              height: 40,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              Checkbox(
                value: isAgree,
                onChanged: (value) {
                  setState(() {
                    isAgree = value;
                  });
                },
              ),
              Text(STATIC_STRING_AGREEMENT,
                  style: TextStyle(fontSize: 14, color: HexColor("#999999")))
            ]),
            Center(
              child: FractionallySizedBox(
                widthFactor: 156 / 375,
                child: RoundedLoadingButton(
                  color: HexColor("#333333"),
                  child: Text(
                    STATIC_STRING_CONFIRM_CREATE,
                    style: TextStyle(color: Colors.white, fontSize: 15),
                  ),
                  successColor: QuhuiColors.mainThemeColor,
                  controller: btnController,
                  onPressed: () {
                    checkConvention();
                  },
                  errorColor: QuhuiColors.textColorRed,
                ),
              ),
            ),
            SizedBox(
              height: 45,
            )
          ],
        ));
  }

  @override
  void unFocusTextField() {
    titleFocusNode.unfocus();
    personCountfocusNode.unfocus();
    costFocusNode.unfocus();
    descFocusNode.unfocus();
  }

  @override
  ActivityCreateRequest getCreateRequestBean(String content) {
    String location;
    String address;
    if (_poiSearch != null) {
      location = '${_poiSearch.longitude},${_poiSearch.latitude}';
      address = _poiSearch.title;
    }
    var createRequest = ActivityCreateRequest(
      aim: titleController.text,
      companyId: 0,
      cost: priceController.text,
      description: content,
      startTime: startTime.millisecondsSinceEpoch ~/ 1000,
      endTime: endTime.millisecondsSinceEpoch ~/ 1000,
      userId: currentUser.uid,
      form: (_activityForm?.value ?? 0) + 1,
      isOnline: _activityIsOnline?.value ?? 0,
      address: address,
      location: location,
      limitPeople: personNumberController.text.isEmpty
          ? 0
          : personNumberController.text.toInt(),
      logo: logoRemote,
      groupId: widget.interestId,
      smallGroupId: widget.circleId,
      type: 2,
      notifyConfig: "1",
    );
    return createRequest;
  }
}
